// markdown to html
const fs = require("fs");
const path = require("path");
var hljs = require("highlight.js");

const md = require("markdown-it")({
	html: true,
	linkify: true,
	typographer: true,
	breaks: true,
	highlight: function (str, lang) {
		if (lang && hljs.getLanguage(lang)) {
			try {
				return (
					'<pre><code class="hljs">' +
					hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
					"</code></pre>"
				);
			} catch (__) {}
		}

		return (
			'<pre><code class="hljs">' + md.utils.escapeHtml(str) + "</code></pre>"
		);
	},
}).use(require("markdown-it-mark"));
// md 转 json
const { parse } = require("himalaya");
function mdToJson(mdPath) {
	let mdFile = null;
	let htmlFile = null;
	let jsonFile = null;
	// 读取 markdown 文件
	if (typeof mdPath === "string") {
		try {
			mdFile = fs.readFileSync(path.resolve(mdPath), { encoding: "utf-8" });
			// md to html
			htmlFile = md.render(mdFile);
			// html to json
			jsonFile = parse(htmlFile);
		} catch (_) {
			console.log(_);
		}
	}
	if (jsonFile) {
		return jsonFile;
	} else {
		return {};
	}
}
module.exports = mdToJson;
